package com.tgy.MyFlowable.workflow.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ctsi.fdProject.model.RewGuardianship;
import com.ctsi.fdProject.service.RewGuardianshipService;
import com.ctsi.system.service.IDictService;
import com.ctsi.workflow.util.BpmEventUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.event.impl.FlowableActivityEventImpl;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 全局多实例活动结束监听器
 *
 * @author mingyuan
 * @version 1.0
 */
@Slf4j
public class GlobalMultiInsActCompletedListener implements FlowableEventListener {
    @SneakyThrows
    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        FlowableActivityEventImpl flowableActivityEvent = (FlowableActivityEventImpl) flowableEvent;
        String scopeDefinitionId = flowableActivityEvent.getScopeDefinitionId();
        String executionId = flowableActivityEvent.getExecutionId();
        String activityId = flowableActivityEvent.getActivityId();
        updateBusiness(scopeDefinitionId, executionId, activityId);
        DelegateExecution execution = flowableActivityEvent.getExecution();
        String eventType = flowableActivityEvent.getType().name();
        //根据事件类型获取脚本并执行
        BpmEventUtil.getAndExecuteScript(execution, eventType);
        log.info(">>> 多实例活动完成了........");
    }

    private void updateBusiness(String scopeDefinitionId, String executionId, String activityId) throws Exception {
        IDictService dictService = SpringUtil.getBean(IDictService.class);
        String value = dictService.getValue("prodefRelation", "parallelReward");
        if (ObjectUtil.isEmpty(value)){
            return;
        }
        if (value.equals(scopeDefinitionId) && activityId.equals("Activity_1lfydyr")) {
            //有奖监护会签节点完成
            RuntimeService runtimeService = SpringUtil.getBean(RuntimeService.class);
            RewGuardianshipService rewGuardianshipService = SpringUtil.getBean(RewGuardianshipService.class);
            String busnessIdStr = (String) runtimeService.getVariable(executionId, "busnessId");
            List<String> busnessIdList = Arrays.stream(busnessIdStr
                    .substring(busnessIdStr.indexOf("[") + 1, busnessIdStr.lastIndexOf(']'))
                    .split(",")).collect(Collectors.toList());
            RewGuardianship rewGuardianship = new RewGuardianship();
            rewGuardianship.setIdList(busnessIdList.stream().map(Double :: parseDouble).map(Double :: longValue).collect(Collectors.toList()));
            rewGuardianship.setUpdateTime(new Date());
            rewGuardianship.setLinkFlag((short)5);
            //检查有奖监护数据是否已经
            boolean checkLinkFlag = rewGuardianshipService.checkLinkFlag(rewGuardianship);
            if (checkLinkFlag) {
                //可以正常更新数据
                boolean update = rewGuardianshipService.batchUpdateLinkFlag(rewGuardianship);
                if (!update) {
                    throw new Exception("有奖监护状态更新失败");
                }
            }
        }
    }

    @Override
    public boolean isFailOnException() {
        return false;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
